<?php
/**
 * #Celebrate Shieh
 *             ,%%%%%%%%,
 *           ,%%/\%%%%/\%%
 *          ,%%%\c "" J/%%%
 * %.       %%%%/ o  o \%%%
 * `%%.     %%%%    _  |%%%
 *  `%%     `%%%%(__Y__)%%'
 *  //       ;%%%%`\-/%%%'
 * ((       /  `%%%%%%%'
 *  \\    .'          |
 *   \\  /       \  | |
 *    \\/         ) | |
 *     \         /_ | |__
 *     (___________))))))) 攻城湿
 *
 *        _       _
 * __   _(_)_   _(_) __ _ _ __
 * \ \ / / \ \ / / |/ _` |'_ \
 *  \ V /| |\ V /| | (_| | | | |
 *   \_/ |_| \_/ |_|\__,_|_| |_|
 */

namespace App\Http\Middleware;

use App\Libs\Code\ErrorCode;
use App\Libs\Redis\RedisLibs;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class Filter
{

    // 两次点击按钮之间的点击间隔不能少于1秒
    private static $MIN_CLICK_DELAY_TIME = 1;

    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param \Closure $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $this->repeat($request);
        $this->remove($request);//去除空
        $this->filter($request);//过滤
        return $next($request);
    }

    /**
     * 过滤
     *
     * @param Request $request
     */
    private function filter($request)
    {
        if ($request->filter != 'true') foreach ($request->all() as $key => $value) $request[$key] = filter((string)$value);//判断是否需要过滤内容
    }

    /**
     * 去除空
     *
     * @param Request $request
     *
     * @return mixed
     */
    private function remove($request)
    {
        foreach ($request->all() as $key => $value) if (!$request->filled($key)) unset($request[$key]);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    private function repeat($request)
    {
        if (Auth::id() && $request->method() != 'GET') {
            $redis = new RedisLibs();
            $key   = 'blog:repeat:time:' . Auth::id();
            $code  = $redis->get($key);
            if ($code) {
                if ($request->ajax()) return data(null, (new ErrorCode())::message(2209), 1000);
                else return back()->with('error', (new ErrorCode())::message(2209));
            }
            $redis->set($key, 'true', static::$MIN_CLICK_DELAY_TIME);
        }
    }

}
